import { ref, watch, onUnmounted, type Ref } from 'vue'
import { useNotesStore } from '@/stores/notes'
import type { Note } from '@/types/note'

/**
 * 自动保存功能
 */
export function useAutoSave(note: Ref<Partial<Note>>, noteId?: string) {
  const notesStore = useNotesStore()
  const isSaving = ref(false)
  const lastSaved = ref<Date | null>(null)
  const hasUnsavedChanges = ref(false)
  const saveTimeout = ref<number | null>(null)
  const autoSaveInterval = 3000 // 3秒自动保存

  // 防抖保存函数
  const debouncedSave = () => {
    if (saveTimeout.value) {
      clearTimeout(saveTimeout.value)
    }

    saveTimeout.value = window.setTimeout(async () => {
      await performSave()
    }, autoSaveInterval)
  }

  // 执行保存
  const performSave = async () => {
    if (!note.value.title?.trim() || !note.value.content?.trim()) {
      return
    }

    try {
      isSaving.value = true
      hasUnsavedChanges.value = false

      if (noteId) {
        // 更新现有笔记
        const success = await notesStore.updateNote(noteId, {
          title: note.value.title,
          content: note.value.content
        })
        
        if (success) {
          lastSaved.value = new Date()
        }
      } else {
        // 创建新笔记
        const newNote = await notesStore.createNote({
          title: note.value.title!,
          content: note.value.content!
        })
        
        if (newNote) {
          lastSaved.value = new Date()
          // 更新路由参数
          window.history.replaceState(null, '', `/editor/${newNote._id}`)
        }
      }
    } catch (error) {
      console.error('自动保存失败:', error)
      hasUnsavedChanges.value = true
    } finally {
      isSaving.value = false
    }
  }

  // 手动保存
  const saveNow = async () => {
    if (saveTimeout.value) {
      clearTimeout(saveTimeout.value)
    }
    return await performSave()
  }

  // 监听内容变化
  watch(
    () => [note.value.title, note.value.content],
    () => {
      if (note.value.title?.trim() && note.value.content?.trim()) {
        hasUnsavedChanges.value = true
        debouncedSave()
      }
    },
    { deep: true }
  )

  // 页面卸载前保存
  const handleBeforeUnload = (event: BeforeUnloadEvent) => {
    if (hasUnsavedChanges.value) {
      event.preventDefault()
      event.returnValue = '您有未保存的更改，确定要离开吗？'
      return '您有未保存的更改，确定要离开吗？'
    }
  }

  // 监听页面卸载事件
  if (typeof window !== 'undefined') {
    window.addEventListener('beforeunload', handleBeforeUnload)
  }

  // 清理函数
  onUnmounted(() => {
    if (saveTimeout.value) {
      window.clearTimeout(saveTimeout.value)
    }
    if (typeof window !== 'undefined') {
      window.removeEventListener('beforeunload', handleBeforeUnload)
    }
  })

  return {
    isSaving,
    lastSaved,
    hasUnsavedChanges,
    saveNow,
    performSave
  }
} 